<?php
/**
 *
 */
class Yz_Template_Layout
    extends Yz_Template_Native
    implements Yz_Template_Interface,Yz_Template_Layout_Interface
{

    protected $content;

    /** pre-rendered included templates (to make their includes available to layout)
     *  @var array
     */
    protected $renderedTemplates = array();


    /**
     *  disable boundary mark output for Layouts
     *  @var null
     */
    protected $boundaryMark;


    /************************************
     *          Public methods          *
     ************************************/

    /** Create and include a template given by module name and template name
     *  @param string $moduleName
     *  @param string $templateName
     *  @return Yz_Template_Interface
     */
    public function createTemplate($templateName, $moduleName=null)
    {
        debug();
        $template = parent::createTemplate($templateName, $moduleName);
        $tplName = $template->className();
        $this->renderedTemplates[$tplName] = $this->doRenderTemplate($template);
        return $template;
    }


    /** assign the content template
     *
     *  @return chainable
     */
    public function assignContent( Yz_Template_Interface $contentTemplate )
    {
        $this->contentTemplate = $contentTemplate;
        return $this;
    }

    /** Render the layout with the $contentTemplate as content
     *  @param Yz_Template_Interface $contentTemplate
     *  @return string
     */
    public function render()
    {
        debug();

        $contentTemplate = $this->contentTemplate;

        $this->value = $contentTemplate->toArray();

        // render the template in case it has not been rendered yet
        $this->content = $contentTemplate->render();

        // take the page head entries from the template AFTER render
        $this->css = $contentTemplate->getCSS();
        $this->js = $contentTemplate->getJS();
        $this->meta = $contentTemplate->getMeta();
        $this->title = $contentTemplate->getTitle();

        return $this->doRender();

        /// ###
        $content = $this->doRender();

        return $content;
    }


    /**
     *  @param Yz_Template_Interface $template
     *  @return string
     */
    protected function doRenderTemplate(Yz_Template_Interface $template)
    {
        debug();
        $tplName = $template->className();
        if (array_key_exists($tplName, $this->renderedTemplates)) {
            $html = $this->renderedTemplates[$tplName];
        } else {
            $html = parent::doRenderTemplate($template);
        }
        return $html;
    }

}
